package priv.utrix.micro.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import priv.utrix.micro.config.GatewayWhiteListConfig;
import priv.utrix.micro.constant.AuthConstants;
import priv.utrix.micro.constant.ResultCode;
import priv.utrix.micro.json.R;
import priv.utrix.micro.utils.RedisUtil;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 黑名单token过滤器
 *
 * @author utrix
 * @since 2020/10/14 17:35
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    final RedisUtil redisUtil;
    final AntPathMatcher antPathMatcher = new AntPathMatcher();
    final GatewayWhiteListConfig gatewayWhiteListConfig;
    final RedisTemplate<String, Object> redisTemplate;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String path = exchange.getRequest().getURI().getPath();
        for (String url : gatewayWhiteListConfig.getUrls()) {
            if (antPathMatcher.match(url, path)) {
                // 请求路径如果是白名单则直接放行
                return chain.filter(exchange);
            }
        }

        // 获取jwt唯一标识
        String jti = exchange.getRequest().getHeaders().getFirst(AuthConstants.JWT_TOKEN_HEADER);
        if (StrUtil.isBlank(jti)) {
            return chain.filter(exchange);
        }

        jti = jti.replace(AuthConstants.JWT_TOKEN_PREFIX, Strings.EMPTY);
        String token = redisUtil.strGet(jti);
        if (StrUtil.isBlank(token)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            response.getHeaders().set("Access-Control-Allow-Origin", "*");
            response.getHeaders().set("Cache-Control", "no-cache");
            String body = JSONUtil.toJsonStr(R.failed(ResultCode.USER_ACCESS_UNAUTHORIZED));
            DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
